<template>
  <div class="container">
    <el-card class="box-card">
     <div slot="header" class="clearfix">
        <span>{{ this.$route.query.id ? '试题编辑' : '试题录入' }}</span>
      </div>
      <el-form ref="ruleFrom" label-width="100px" :model="ruleFrom" :rules="rules">
        <!-- 学科 -->
        <el-form-item label="学科" prop="subjectID">
          <el-select v-model="ruleFrom.subjectID" placeholder="请选择" @change="changeoption">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录" prop="catalogID">
          <el-select v-model="ruleFrom.catalogID" placeholder="请选择">
            <el-option
              v-for="item in directory"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="ruleFrom.enterpriseID" placeholder="请选择">
            <el-option
              v-for="item in enterprise"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select
            class="option"
            v-model="ruleFrom.province"
            placeholder="请选择"
            @change="changeoptionss"
          >
            <el-option v-for="item in citySelect.province" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
          <el-select class="option options" v-model="ruleFrom.city" placeholder="请选择">
            <el-option v-for="item in citySelect.cityDate" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-select v-model="ruleFrom.direction">
            <el-option v-for="item in directionss" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 单选框-->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group @change="changeRadio({})" v-model="ruleFrom.questionType">
            <el-radio v-for="item in questionType" :key="item.value" :label="item.value + ''">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 单选框-->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="ruleFrom.difficulty">
            <el-radio v-for="item in difficulty" :key="item.value" :label="item.value + ''">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干" prop="question">
          <quill-editor
            @blur="checkInput"
            v-model="ruleFrom.question"
            :options="editorOptions"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="选项：" prop="options" v-if="ruleFrom.questionType !== '3'">
          <div class="option_item" v-for="(item, index) in ruleFrom.options" :key="item.code">
            <el-radio
              v-if="ruleFrom.questionType === '1'"
              @change="changeRadio(item)"
              v-model="item.isRight"
              style="margin-right:0"
              :label="true"
              >{{ item.code }}：</el-radio
            >
            <el-checkbox
              v-if="ruleFrom.questionType === '2'"
              v-model="item.isRight"
              style="margin-right:0"
              :label="true"
              >{{ item.code }}：</el-checkbox
            >
            <el-input v-model="item.title" style="width:240px"></el-input>
            <div class="upload"  @click="getIndex(index)">
              <el-upload
                :http-request="upload"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
              >
                <img v-if="item.img" :src="item.img" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <i class="el-icon-circle-close close " @click="del(item.code, index)"></i>
            </div>
          </div>
          <el-row>
            <el-button
              type="danger"
              :disabled="ruleFrom.questionType !== '2'"
              @click="addOption"
              size="small"
              >+增加选项与答案</el-button
            >
          </el-row>
        </el-form-item>
        <!-- 解析视频 输入框-->
        <el-form-item label="解析视频：">
          <el-input v-model="ruleFrom.videoURL" style="width:400px"></el-input>
        </el-form-item>

        <!-- 答案解析  富文本 -->
        <el-form-item label="答案解析：" prop="question">
          <quill-editor @blur="checkInput" v-model="ruleFrom.answer" :options="editorOptions">
          </quill-editor>
        </el-form-item>

        <!-- 题目备注 文本域-->
        <el-form-item label="题目备注：">
          <el-input
            type="textarea"
            :rows="4"
            v-model="ruleFrom.remarks"
            style="width:400px"
          ></el-input>
        </el-form-item>
        <!-- 试题标签 输入框-->
        <el-form-item label="试题标签：">
          <el-select
            style="width:400px"
            v-model="ruleFrom.tags"
            multiple
            placeholder="请选择试题标签"
          >
            <el-option
              v-for="item in tagsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 提交按钮-->
        <el-form-item>
          <el-button @click="submit()" type="primary">确认提交</el-button>

          <!-- <el-button v-if="!$route.query.id" @click="submit()" type="primary">确认提交</el-button> -->
          <!-- <el-button v-else @click="update()" type="success">确认修改</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 引入必要的COS模块
import { simple } from '@/api/hmmm/subjects.js'
import { simple as CatalogList } from '@/api/hmmm/directorys.js'
import { list as enterprisess } from '@/api/hmmm/companys.js'
// 市 县
import { provinces, citys } from '@/api/hmmm/citys.js'
// 方向
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// 标签
import { simple as getTags } from '@/api/hmmm/tags'
// 提交
import { add, detail, update } from '@/api/hmmm/questions.js'
const COS = require('cos-js-sdk-v5')
// 实例化对象

var cos = new COS({
  SecretId: 'AKIDtb5LM9nDNcbLq55qLbcNtDqEOIxMWR7Y',
  SecretKey: 'EDy2sSoumjZP8ew10kHaeT3OUTEk13qO'
})
export default {
  data () {
    return {
      imageUrl: '',
      // 学科数据
      options: [],
      // 目录数据
      directory: [],
      // 企业数据
      enterprise: [],
      // 城市数据
      // 城市地区列表
      citySelect: {
        province: [],
        cityDate: []
      },
      // 题型
      questionType,
      // 难度
      difficulty,
      // 地区列表
      directionss: direction,
      // 标签选项
      tagsOptions: [],
      ruleFrom: {
        number: '', // 试题编号 ， 后端生成
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        // 题干
        question: null,
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        isPerfect: '' // 是否精选题 ， 后台自动生成
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }]
      },
      // 富文本配置
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ]
        }
      }
    }
  },
  components: {},
  mounted () {
    this.createAPI()
    this.enterprises()
    this.getCityData()
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  methods: {
    // 从精选题库修改跳到试题录入,数据回显
    async getQuestion () {
      // data结构
      const { data } = await detail({ id: this.$route.query.id })
      // console.log({ data }, typeof (data.tags))
      data.tags = data.tags.toString()
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.ruleFrom = data
      const res = await CatalogList({ subjectID: this.ruleFrom.subjectID })
      this.directory = res.data
      const resp = await getTags({ subjectID: this.ruleFrom.subjectID })
      this.tagsOptions = resp.data
      // // 滚动顶部
      // this.$nextTick(() => {
      //   window.scrollTo(0, 0)
      // })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 获取试题列表
    async createAPI () {
      const { data } = await simple()
      this.options = data
    },
    // 获取目录列表
    async changeoption () {
      this.ruleFrom.catalogID = ''
      this.ruleFrom.tags = ''
      const { data } = await CatalogList({ subjectID: this.ruleFrom.subjectID })
      this.directory = data
      // 试题标签 列表
      const resp = await getTags({ subjectID: this.ruleFrom.subjectID })
      this.tagsOptions = resp.data
    },
    // 获取企业列表
    async enterprises () {
      const { data } = await enterprisess()
      // console.log(data.items)
      this.enterprise = data.items
    },
    // 获取城市数据
    getCityData () {
      this.citySelect.province = provinces()
    },
    // 获取县数据
    changeoptionss (e) {
      // 当市变化让县为空
      this.ruleFrom.city = ''
      this.citySelect.cityDate = citys(e)
      // 调用city校验规则
      this.$refs.ruleFrom.validateField('city')
    },
    // 选择题型 ,改变单选框
    changeRadio (item) {
      // 1. 清除所有的选中
      this.ruleFrom.options.forEach(item => {
        item.isRight = false
      })
      // 2. 自己选中
      item.isRight = true
    },
    // 添加选项
    addOption () {
      this.ruleFrom.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.ruleFrom.options.length),
        title: ''
      })
    },
    // 删除一行图片
    del (code, index) {
      console.log(code)
      if (code === 'A' || code === 'B' || code === 'C' || code === 'D') {
        return this.$message('禁止删除默认选项')
      }
      this.ruleFrom.options = this.ruleFrom.options.filter((item, nindex) => {
        if (nindex !== index) {
          return item
        }
      })
    },
    // 富文本输入,校验,写入后鼠标离开,校验提示消失
    checkInput () {
      // 调用el-form组件的 validateField 校验  question  字段
      this.$refs.ruleFrom.validateField('question')
    },
    // 提交 编辑
    submit () {
      this.$refs.ruleFrom.validate(async valid => {
        if (!valid) return
        if (this.ruleFrom.id) {
          await update({ ...this.ruleFrom, tags: this.ruleFrom.tags.toString() })
        } else {
          await add({ ...this.ruleFrom, tags: this.ruleFrom.tags.toString() })
        }
        // await add(this.ruleFrom)
        this.$message.success(`${this.ruleFrom.id ? '编辑' : '新增'}成功`)
        this.$router.push('/questions/list')
      })
    },
    // options对应的下标
    getIndex (i) {
      console.log(i, 89999999999)

      this.index = i
    },
    // 自定义上传属性
    upload (res) {
      // console.log(i)
      if (res.file) {
        cos.putObject(
          {
            Bucket: 'zijiewei-1302472828' /* 存储桶名称 必须 */,
            Region:
              'ap-beijing' /* 存储桶所在地域，必须字段 `            Key: res.file.name /* 文件名 必须 */,
            Key: res.file.name /* 文件名 */,
            StorageClass: 'STANDARD', // 上传模式, 标准模式
            Body: res.file // 上传文件对象
          },
          (err, data) => {
            console.log(err || data)
            // 上传成功之后
            if (data.statusCode === 200) {
              this.ruleFrom.options[this.index].img = `https:${data.Location}`
            }
          })
      }
    }
  }
}
</script>

<style scoped lang="css">
.el-select {
  width: 400px;
  height: 36px;
}
.option {
  width: 198px;
}
.option_item {
  padding-bottom: 20px;
}
.options {
  margin-left: 3.5px;
}
.close {
  position: absolute;
  right: 0;
  top: 0;
  -webkit-transform: translate(50%, -50%);
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}

/* .el-radio{
  display: block;
} */
.radio {
  display: block;
}
.upload {
  width: 100px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  left: 290px;
  top: -50px;
  text-align: center;
}
.close {
  position: absolute;
  right: -5px;
  top: 0;
  -webkit-transform: translate(50%, -50%);
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.el-upload_input {
  position: relative;
  top: -50px;
  display: none !important;
}
.cover-img {
  width: 100px;
  height: 50px;
  object-fit: cover;
}
.avatar {
  height: 60px;
}
</style>
